package com.leyou.user.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.utils.NumberUtils;
import com.leyou.user.config.PasswordConfig;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.mapper.UserMapper;
import com.sun.org.apache.xalan.internal.lib.ExsltBase;
import com.sun.org.apache.xml.internal.resolver.readers.ExtendedXMLCatalogReader;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;
import java.util.HashMap;
import java.util.Map;

import static com.leyou.common.constants.MQConstants.Exchange.SMS_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.RoutingKey.VERIFY_CODE_KEY;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 校验数据是否可用
     * @param data
     * @param type
     * @return
     */
    public Boolean checkData(String data, Integer type) {

        //TODO 还要判断type，type只能是1，或者2
        //1是用户名，2是手机号
        //StringUtils.isBlank(data) || !(type ==1 || type ==2)
        //校验手机号
        if (StringUtils.isBlank(data)){
            throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }

        //判断数据类型
        User record = new User();
        switch (type){
            case 1:
                record.setUsername(data);
                break;
            case 2:
                record.setPhone(data);
                break;
            default:
                throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }

        boolean result = false;
        try {
            //查询用户是否存在
            result = this.userMapper.selectCount(record) != 1;
        } catch (Exception e) {
            throw new LyException(ExceptionEnum.DATA_SERVER_BOOM);
        }

        return result;
    }

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    String KEY_PREFIX = "ly:verify:phone:";
    /**
     * 发送短信验证码
     * @param phone
     */
    public void sendCode(String phone) {

        //TODO 对数据进行校验
        Map<String, String> msg = new HashMap<>();
        msg.put("phone",phone);

        //随机生成6位随机验证码
        String code = NumberUtils.generateCode(6);
        msg.put("code",code);

        //调用短信服务接口发送短信（交换机，RoutingKey,消息体）
        amqpTemplate.convertAndSend(SMS_EXCHANGE_NAME, VERIFY_CODE_KEY, msg);

        //在服务端将数据保存到redis中
        redisTemplate.opsForValue().set(KEY_PREFIX + phone,code,5,TimeUnit.MINUTES);
    }

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    /**
     * 注册用户，验证、加密
     * @param user
     * @param code
     */
    public void register(User user, String code) {

        String key = KEY_PREFIX + user.getPhone();

        //1.校验验证码
        //1.1取出redis中的验证码
        if (!redisTemplate.hasKey(key)){
            throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }
        String cacheCode = redisTemplate.opsForValue().get(key);
        //1.2比较验证码
        if (StringUtils.isBlank(cacheCode) || !StringUtils.equals(code,cacheCode)){
            throw new LyException(ExceptionEnum.INVALID_VERIFY_CODE);
        }
        //2.对密码加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        //3.写入数据库
        int count = userMapper.insertSelective(user);
        if (1 != count){
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }

        //注册完成后，建议将redis中的验证码删除，如果过期时间在3秒内，不需要删除
        //存在，并且过期时间足够，超过3秒，删除
        if(redisTemplate.hasKey(key) && redisTemplate.getExpire(key,TimeUnit.SECONDS) >3){
            redisTemplate.delete(key);
        }
    }

    /**
     *通过用户名和密码查询用户信息
     * @param username
     * @param password
     * @return
     */
    public UserDTO queryUserByUsernameAndPassword(String username, String password) {
        //1.根据用户名查询
        User u = new User();
        u.setUsername(username);
        User user = userMapper.selectOne(u);

        //2.判断是否存在
        if (user == null){
            //用户名错误
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }

        //3.校验密码
        if (!passwordEncoder.matches(password,user.getPassword())){
            //密码错误
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }

        return BeanHelper.copyProperties(user,UserDTO.class);
    }
}